const fs = require('fs').promises;
const path = require('path');
const ExcelJS = require('exceljs');
const config = require('../config/config');
const { setupLogger } = require('../utils/logger');

class StorageService {
  constructor() {
    this.logger = setupLogger();
    this.isInitialized = false;
  }

  async initialize() {
    try {
      this.logger.info('初始化存储服务...');
      
      // 确保数据目录存在
      await this.ensureDataDirectory();
      
      this.isInitialized = true;
      this.logger.info('存储服务初始化完成');
    } catch (error) {
      this.logger.error('存储服务初始化失败:', error);
      throw error;
    }
  }

  async ensureDataDirectory() {
    try {
      await fs.access(config.storage.dataDir);
    } catch {
      await fs.mkdir(config.storage.dataDir, { recursive: true });
      this.logger.info(`创建数据目录: ${config.storage.dataDir}`);
    }
  }

  async saveData(processedData) {
    if (!this.isInitialized) {
      throw new Error('存储服务未初始化');
    }

    try {
      this.logger.info('开始保存数据...');
      
      // 并行保存JSON和Excel文件
      const savePromises = [
        this.saveToJson(processedData),
        this.saveToExcel(processedData)
      ];
      
      await Promise.all(savePromises);
      
      this.logger.info('数据保存完成');
      return {
        success: true,
        jsonFile: path.join(config.storage.dataDir, config.storage.jsonFile),
        excelFile: path.join(config.storage.dataDir, config.storage.excelFile),
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      this.logger.error('数据保存失败:', error);
      throw error;
    }
  }

  async saveToJson(data) {
    try {
      const jsonPath = path.join(config.storage.dataDir, config.storage.jsonFile);
      
      // 添加元数据
      const jsonData = {
        metadata: {
          version: '1.0.0',
          generatedAt: new Date().toISOString(),
          dataCount: data.dataCount,
          source: 'crypto-aggregator'
        },
        summary: data.summary,
        tokens: data.tokens,
        smartMoney: data.smartMoney,
        marketData: data.marketData,
        trends: data.trends,
        risks: data.risks,
        lastUpdate: data.lastProcessed
      };
      
      // 格式化JSON输出
      const jsonString = JSON.stringify(jsonData, null, 2);
      
      // 写入文件
      await fs.writeFile(jsonPath, jsonString, 'utf8');
      
      this.logger.info(`JSON数据已保存到: ${jsonPath}`);
      
      // 保存压缩版本（用于API快速访问）
      const compactJsonPath = path.join(config.storage.dataDir, 'compact_' + config.storage.jsonFile);
      const compactData = {
        metadata: jsonData.metadata,
        summary: jsonData.summary,
        tokens: jsonData.tokens.slice(0, 50), // 只保留前50个代币
        smartMoney: jsonData.smartMoney.slice(0, 20), // 只保留前20个聪明钱
        lastUpdate: jsonData.lastUpdate
      };
      
      await fs.writeFile(compactJsonPath, JSON.stringify(compactData), 'utf8');
      this.logger.info(`压缩JSON数据已保存到: ${compactJsonPath}`);
      
    } catch (error) {
      this.logger.error('JSON保存失败:', error);
      throw error;
    }
  }

  async saveToExcel(data) {
    try {
      const excelPath = path.join(config.storage.dataDir, config.storage.excelFile);
      
      // 创建工作簿
      const workbook = new ExcelJS.Workbook();
      workbook.creator = 'Crypto Aggregator';
      workbook.lastModifiedBy = 'System';
      workbook.created = new Date();
      workbook.modified = new Date();
      
      // 创建概览工作表
      await this.createSummarySheet(workbook, data);
      
      // 创建代币分析工作表
      await this.createTokensSheet(workbook, data.tokens);
      
      // 创建聪明钱工作表
      await this.createSmartMoneySheet(workbook, data.smartMoney);
      
      // 创建市场数据工作表
      await this.createMarketDataSheet(workbook, data.marketData);
      
      // 创建趋势分析工作表
      await this.createTrendsSheet(workbook, data.trends);
      
      // 创建风险分析工作表
      await this.createRisksSheet(workbook, data.risks);
      
      // 保存文件
      await workbook.xlsx.writeFile(excelPath);
      
      this.logger.info(`Excel数据已保存到: ${excelPath}`);
      
    } catch (error) {
      this.logger.error('Excel保存失败:', error);
      throw error;
    }
  }

  async createSummarySheet(workbook, data) {
    const worksheet = workbook.addWorksheet('概览', {
      headerFooter: { firstHeader: '加密货币数据聚合系统 - 概览' }
    });
    
    // 设置列宽
    worksheet.columns = [
      { header: '指标', key: 'metric', width: 25 },
      { header: '数值', key: 'value', width: 20 },
      { header: '说明', key: 'description', width: 40 }
    ];
    
    // 添加标题
    worksheet.mergeCells('A1:C1');
    worksheet.getCell('A1').value = '数据概览';
    worksheet.getCell('A1').font = { size: 16, bold: true };
    worksheet.getCell('A1').alignment = { horizontal: 'center' };
    
    // 添加数据
    const summaryData = [
      { metric: '生成时间', value: data.summary.generatedAt, description: '数据生成时间' },
      { metric: '代币总数', value: data.summary.totalTokens, description: '分析的代币数量' },
      { metric: '聪明钱钱包数', value: data.summary.totalSmartWallets, description: '识别的聪明钱钱包数量' },
      { metric: '数据源数量', value: data.dataCount.total, description: '原始数据条数' },
      { metric: '清洗后数据', value: data.dataCount.cleaned, description: '清洗后的有效数据条数' }
    ];
    
    summaryData.forEach((row, index) => {
      const rowNum = index + 3;
      worksheet.getCell(`A${rowNum}`).value = row.metric;
      worksheet.getCell(`B${rowNum}`).value = row.value;
      worksheet.getCell(`C${rowNum}`).value = row.description;
    });
    
    // 设置样式
    worksheet.getRow(2).font = { bold: true };
    worksheet.getRow(2).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' }
    };
    
    // 添加边框
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 1) {
        row.eachCell((cell) => {
          cell.border = {
            top: { style: 'thin' },
            left: { style: 'thin' },
            bottom: { style: 'thin' },
            right: { style: 'thin' }
          };
        });
      }
    });
  }

  async createTokensSheet(workbook, tokens) {
    const worksheet = workbook.addWorksheet('代币分析');
    
    // 设置列
    worksheet.columns = [
      { header: '排名', key: 'rank', width: 8 },
      { header: '代币符号', key: 'symbol', width: 12 },
      { header: '代币名称', key: 'name', width: 20 },
      { header: '平均价格', key: 'avgPrice', width: 15 },
      { header: '24h价格变化%', key: 'avgPriceChange24h', width: 18 },
      { header: '平均交易量', key: 'avgVolume24h', width: 18 },
      { header: '平均市值', key: 'avgMarketCap', width: 18 },
      { header: '数据源数量', key: 'sourceCount', width: 12 },
      { header: '综合评分', key: 'score', width: 12 },
      { header: '分类', key: 'category', width: 12 },
      { header: '风险因素', key: 'riskFactors', width: 20 }
    ];
    
    // 添加数据
    tokens.forEach((token, index) => {
      worksheet.addRow({
        rank: index + 1,
        symbol: token.symbol,
        name: token.name,
        avgPrice: token.avgPrice ? parseFloat(token.avgPrice.toFixed(6)) : 0,
        avgPriceChange24h: token.avgPriceChange24h ? parseFloat(token.avgPriceChange24h.toFixed(2)) : 0,
        avgVolume24h: token.avgVolume24h ? parseInt(token.avgVolume24h) : 0,
        avgMarketCap: token.avgMarketCap ? parseInt(token.avgMarketCap) : 0,
        sourceCount: token.sourceCount,
        score: token.score ? parseFloat(token.score.toFixed(1)) : 0,
        category: token.category,
        riskFactors: token.riskFactors.join(', ')
      });
    });
    
    // 设置表头样式
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF4472C4' }
    };
    headerRow.font = { color: { argb: 'FFFFFFFF' }, bold: true };
    
    // 设置数字格式
    worksheet.getColumn('avgPrice').numFmt = '#,##0.000000';
    worksheet.getColumn('avgPriceChange24h').numFmt = '#,##0.00"%"';
    worksheet.getColumn('avgVolume24h').numFmt = '#,##0';
    worksheet.getColumn('avgMarketCap').numFmt = '#,##0';
    worksheet.getColumn('score').numFmt = '#,##0.0';
    
    // 添加条件格式
    worksheet.addConditionalFormatting({
      ref: `I2:I${tokens.length + 1}`,
      rules: [
        {
          type: 'colorScale',
          cfvo: [
            { type: 'min' },
            { type: 'max' }
          ],
          color: [
            { argb: 'FFFF0000' },
            { argb: 'FF00FF00' }
          ]
        }
      ]
    });
  }

  async createSmartMoneySheet(workbook, smartMoney) {
    const worksheet = workbook.addWorksheet('聪明钱分析');
    
    worksheet.columns = [
      { header: '排名', key: 'rank', width: 8 },
      { header: '钱包地址', key: 'address', width: 25 },
      { header: '昵称', key: 'nickname', width: 15 },
      { header: '7天PnL', key: 'avgPnl7d', width: 15 },
      { header: '30天PnL', key: 'avgPnl30d', width: 15 },
      { header: '胜率', key: 'winRate', width: 12 },
      { header: '总交易数', key: 'totalTrades', width: 12 },
      { header: '平均持有时间', key: 'avgHoldTime', width: 15 },
      { header: '总交易量', key: 'totalVolume', width: 18 },
      { header: '智能评分', key: 'smartScore', width: 12 },
      { header: '风险等级', key: 'riskLevel', width: 12 },
      { header: '标签', key: 'tags', width: 20 }
    ];
    
    smartMoney.forEach((wallet, index) => {
      worksheet.addRow({
        rank: index + 1,
        address: wallet.address,
        nickname: wallet.nickname || '',
        avgPnl7d: wallet.avgPnl7d || 0,
        avgPnl30d: wallet.avgPnl30d || 0,
        winRate: wallet.metrics.winRate ? parseFloat((wallet.metrics.winRate * 100).toFixed(1)) : 0,
        totalTrades: wallet.metrics.totalTrades || 0,
        avgHoldTime: wallet.metrics.avgHoldTime || 0,
        totalVolume: wallet.metrics.totalVolume || 0,
        smartScore: wallet.smartScore ? parseFloat(wallet.smartScore.toFixed(1)) : 0,
        riskLevel: wallet.riskLevel,
        tags: wallet.tags.join(', ')
      });
    });
    
    // 设置表头样式
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF70AD47' }
    };
    headerRow.font = { color: { argb: 'FFFFFFFF' }, bold: true };
    
    // 设置数字格式
    worksheet.getColumn('avgPnl7d').numFmt = '#,##0.00';
    worksheet.getColumn('avgPnl30d').numFmt = '#,##0.00';
    worksheet.getColumn('winRate').numFmt = '#,##0.0"%"';
    worksheet.getColumn('totalVolume').numFmt = '#,##0';
    worksheet.getColumn('smartScore').numFmt = '#,##0.0';
  }

  async createMarketDataSheet(workbook, marketData) {
    const worksheet = workbook.addWorksheet('市场数据');
    
    if (marketData.overview) {
      worksheet.columns = [
        { header: '指标', key: 'metric', width: 25 },
        { header: '数值', key: 'value', width: 20 }
      ];
      
      const overviewData = [
        { metric: '总市值', value: marketData.overview.totalMarketCap?.usd || 0 },
        { metric: '24h交易量', value: marketData.overview.totalVolume?.usd || 0 },
        { metric: '24h市值变化%', value: marketData.overview.marketCapChange24h || 0 },
        { metric: '活跃加密货币数量', value: marketData.overview.activeCryptocurrencies || 0 },
        { metric: '市场数量', value: marketData.overview.markets || 0 }
      ];
      
      overviewData.forEach(row => {
        worksheet.addRow(row);
      });
      
      // 设置表头样式
      const headerRow = worksheet.getRow(1);
      headerRow.font = { bold: true };
      headerRow.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFC000' }
      };
    }
  }

  async createTrendsSheet(workbook, trends) {
    const worksheet = workbook.addWorksheet('趋势分析');
    
    worksheet.columns = [
      { header: '类型', key: 'type', width: 15 },
      { header: '方向', key: 'direction', width: 12 },
      { header: '强度', key: 'strength', width: 12 },
      { header: '变化率', key: 'change', width: 15 },
      { header: '说明', key: 'description', width: 30 }
    ];
    
    const trendData = [
      {
        type: '价格趋势',
        direction: trends.price?.direction || 'neutral',
        strength: trends.price?.strength || 'low',
        change: trends.price?.change ? parseFloat((trends.price.change * 100).toFixed(2)) : 0,
        description: '基于最近价格数据的趋势分析'
      },
      {
        type: '交易量趋势',
        direction: trends.volume?.direction || 'neutral',
        strength: trends.volume?.strength || 'low',
        change: trends.volume?.change ? parseFloat((trends.volume.change * 100).toFixed(2)) : 0,
        description: '基于最近交易量数据的趋势分析'
      }
    ];
    
    trendData.forEach(row => {
      worksheet.addRow(row);
    });
    
    // 设置表头样式
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF9966CC' }
    };
    headerRow.font = { color: { argb: 'FFFFFFFF' }, bold: true };
  }

  async createRisksSheet(workbook, risks) {
    const worksheet = workbook.addWorksheet('风险分析');
    
    worksheet.columns = [
      { header: '风险类型', key: 'type', width: 15 },
      { header: '严重程度', key: 'severity', width: 12 },
      { header: '相关代币', key: 'token', width: 15 },
      { header: '描述', key: 'description', width: 40 }
    ];
    
    risks.forEach(risk => {
      worksheet.addRow(risk);
    });
    
    // 设置表头样式
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFF0000' }
    };
    headerRow.font = { color: { argb: 'FFFFFFFF' }, bold: true };
    
    // 根据严重程度设置行颜色
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 1) {
        const severity = row.getCell(2).value;
        let fillColor = 'FFFFFFFF';
        
        switch (severity) {
          case 'critical':
            fillColor = 'FFFF6B6B';
            break;
          case 'high':
            fillColor = 'FFFFA500';
            break;
          case 'medium':
            fillColor = 'FFFFFF99';
            break;
          case 'low':
            fillColor = 'FF90EE90';
            break;
        }
        
        row.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: fillColor }
        };
      }
    });
  }

  async loadData() {
    try {
      const jsonPath = path.join(config.storage.dataDir, config.storage.jsonFile);
      const data = await fs.readFile(jsonPath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      this.logger.error('加载数据失败:', error);
      return null;
    }
  }

  async loadCompactData() {
    try {
      const compactJsonPath = path.join(config.storage.dataDir, 'compact_' + config.storage.jsonFile);
      const data = await fs.readFile(compactJsonPath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      this.logger.warn('加载压缩数据失败，尝试加载完整数据');
      return await this.loadData();
    }
  }

  async getFileStats() {
    try {
      const jsonPath = path.join(config.storage.dataDir, config.storage.jsonFile);
      const excelPath = path.join(config.storage.dataDir, config.storage.excelFile);
      
      const stats = {};
      
      try {
        const jsonStats = await fs.stat(jsonPath);
        stats.json = {
          exists: true,
          size: jsonStats.size,
          modified: jsonStats.mtime
        };
      } catch {
        stats.json = { exists: false };
      }
      
      try {
        const excelStats = await fs.stat(excelPath);
        stats.excel = {
          exists: true,
          size: excelStats.size,
          modified: excelStats.mtime
        };
      } catch {
        stats.excel = { exists: false };
      }
      
      return stats;
    } catch (error) {
      this.logger.error('获取文件统计失败:', error);
      return {};
    }
  }
}

module.exports = new StorageService();

